import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElCard, ElInput, ElSpace, ElLink, ElMessageBox, ElMessage } from 'element-plus'
import type { TableType } from './typings'
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import { isURL } from '~/utils/validate'

export default defineComponent({
  props: ['batchNum', 'discriminateArr'],
  setup(props, { expose }) {
    const userState = useVuexGetters('user', ['permission']) // 按钮权限
    const store = useStore()
    const proSaasTableRef = ref()
    const state = reactive({
      matchName: '',
      tableList: [],
      buildAreas: ''
    })
    const columns: TableColumnProps<TableType>[] = [
      {
        label: '站点名称',
        prop: 'matchName',
        minWidth: 200,
        sortable: true,
        align: 'center'
      },
      {
        label: '规划站号',
        prop: 'matchNum',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>
            {row.buildStatus === 1 ? <div style="color: red;">{row.matchNum}</div> : row.matchNum}
          </>
        )
      },
      {
        label: '需求类型',
        prop: 'requirementType',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>{row.requirementType === 2 ? <div style="color: blue;">特批</div> : '常规'}</>
        )
      },
      {
        label: '是否加入摘牌',
        prop: 'isDelisting',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>{row.isDelisting === 0 ? <div style="color: blue;">否</div> : '是'}</>
        )
      },
      {
        label: '查勘人',
        prop: 'surveyorName',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '查勘备注',
        prop: 'surveyorMemo',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '查看全景',
        prop: 'overallViewUrl',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>
            {isURL(row.overallViewUrl) ? (
              <a href={row.overallViewUrl} target="_blank" style="cursor: pointer; color: blue;">
                查看全景
              </a>
            ) : (
              '-'
            )}
          </>
        )
      },
      {
        label: '操作',
        prop: 'options',
        align: 'center',
        width: 160,
        render: ({ row }) => (
          <ElSpace>
            {row.isDelisting === 0 && userState.permission.value.has('basebuild_batch_add') && (
              <ElLink type="primary" onClick={() => onDelistingLibrary(row)}>
                <AliIcon type="icon-jiaru" />
                &nbsp;加入摘牌库&nbsp;&nbsp;
              </ElLink>
            )}
            {row.isDelisting === 1 && '已入库'}
          </ElSpace>
        )
      }
    ]

    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') index()
    }
    // 清空搜索
    const clearSearchTable = async () => {
      setTimeout(() => {
        index()
      }, 100)
    }

    const index = async () => {
      const { code, data } = await store.dispatch('base/GetBasebuildbatchBatchMatchList', {
        batchNum: props.batchNum,
        matchName: state.matchName,
        buildAreas: state.buildAreas,
        size: 1000
      })
      if (code === 200) {
        state.tableList = data.records
      }
    }
    //  工区搜索
    const buildAreasAjax = (buildAreas: string) => {
      state.buildAreas = buildAreas
      index()
    }

    //  加入摘牌库
    const onDelistingLibrary = (row: TableType) => {
      ElMessageBox.confirm('是否加入摘牌库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, msg } = await store.dispatch('base/GetBasebuildbatchAddDelisting', {
            assetBaseBuildId: row.id
          })
          if (code === 200) {
            index()
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
          } else {
            ElMessageBox.confirm(msg, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作'
          })
        })
    }

    onMounted(() => {
      state.buildAreas = props.discriminateArr
      index()
    })
    expose({ buildAreasAjax })
    return () => (
      <ElCard>
        <ProSaasTable<TableType>
          ref={proSaasTableRef}
          tableId="SurveyTable"
          columns={columns}
          needPagination={false}
          data={state.tableList}
          height={540}
          headerTitle={
            <>
              <ElInput
                v-model={state.matchName}
                {...{ maxlength: 30 }}
                placeholder="站点名称 回车搜索"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
                style="width: 240px;"
              />
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span>
                共计 <span style="color: #4073ff;">{state.tableList?.length}</span> 条数据
              </span>
            </>
          }
        ></ProSaasTable>
      </ElCard>
    )
  }
})
